package com.atguigu.web;

import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;
import com.atguigu.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {
    private UserService userService=new UserServiceImpl();

    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数
        String username=req.getParameter("username");
        //调用service方法
        boolean existsUsername = userService.existsUsername(username);
        //把结果封装为map对象
        Map<String,Object> map=new HashMap<>();
        map.put("existsUsername",existsUsername);
        Gson gson=new Gson();
        String s = gson.toJson(map);

        resp.getWriter().write(s);
    }

    /**
     *          登录方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        //获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //处理事务
        User login = userService.login(new User(null, username, password, null));
        if (login == null) {
            //把错误信息  和回写表单项   存储到request里面
//            req.setCharacterEncoding("UTF-8");
            req.setAttribute("msg","用户或密码错误！");
            req.setAttribute("username",username);
            //跳回登录页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        } else {
            //把账号密码保存到session中
            req.getSession().setAttribute("user",login);
            //跳到登录成功页面

            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
        }
    }

    /**
     * 注销用户账号
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //销毁session 中（或者删除内容）
        req.getSession().invalidate();
        //重定向到登录页面或者首页面
        resp.sendRedirect(req.getContextPath());
    }
    /**
     *       注册方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //  1、获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");


        User user= WebUtils.copeParamToBean(req.getParameterMap(),new User());
        System.out.println(user.getUsername());
        //获取验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //立刻删除session
        req.getSession().invalidate();
//        2、检查 验证码是否正确  === 写死,要求验证码为:abcde
        if (token.equalsIgnoreCase(code)&&token!=null) {
//        3、检查 用户名是否可用
            if (userService.existsUsername(username)) {
                System.out.println("用户名[" + username + "]已存在!");
                //把回显信息 保存到request
                req.setAttribute("msg","用户名已存在！！");
                //回写username Email
                req.setAttribute("username",username);
                req.setAttribute("email",email);

//        跳回注册页面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
            } else {
                // 可用
//                调用Sservice保存到数据库
                userService.registUser(new User(null, username, password, email));
//
//        跳到注册成功页面 regist_success.jsp
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
            }
        } else {
            //把回显信息 保存到request
            req.setAttribute("msg","验证码错误！！");
            //回写username Email
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            System.out.println("验证码[" + code + "]错误");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }
}
